package com.campus.merchant.service;

import com.campus.common.message.OrderCancelMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * 订单取消消息生产者
 * 负责向Kafka发送订单取消消息
 */
@Service
@Slf4j
public class OrderCancelMessageProducer {

    private static final String TOPIC_ORDER_CANCEL = "order-cancel";

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;
    @Resource
    private ObjectMapper objectMapper;

    /**
     * 发送订单取消消息
     * @param openId 用户openId
     * @param orderId 订单号
     * @param orderAmount 订单金额
     * @param cancelReason 取消原因
     */
    public void sendOrderCancelMessage(String openId, String orderId, BigDecimal orderAmount, String cancelReason) {
        try {
            OrderCancelMessage message = new OrderCancelMessage(openId, orderId, orderAmount, cancelReason);

            String messageJson = objectMapper.writeValueAsString(message);
            
            ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(TOPIC_ORDER_CANCEL, orderId, messageJson);
            
            future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
                @Override
                public void onSuccess(SendResult<String, Object> result) {
                    log.info("订单取消消息发送成功，订单号: {}, 用户openId: {}, offset: {}", 
                            orderId, openId, result.getRecordMetadata().offset());
                }

                @Override
                public void onFailure(Throwable ex) {
                    log.error("订单取消消息发送失败，订单号: {}, 用户openId: {}", orderId, openId, ex);
                }
            });
        } catch (Exception e) {
            log.error("发送订单取消消息异常，订单号: {}, 用户openId: {}", orderId, openId, e);
        }
    }
}